<?php

namespace app\admin\controller\shopro\user;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 会员组管理
 *
 * @icon fa fa-users
 */
class Group extends Backend
{
    /**
     * @var \app\admin\model\shopro\user\Group
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\shopro\user\Group;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(['is_vip'=>2])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where(['is_vip'=>2])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $list   = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            $this->success('用户组', null, $result);
        }
        return $this->view->fetch();
    }

    /**
     * 获取vip分组
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserVipGroup()
    {
        $list = Db::name('user_group')
            ->where(['is_vip' => 2])
            ->field(['id', 'name'])
            ->order('id ASC')
            ->select();

        return json([
            'code' => 1,
            'msg'  => '获取成功',
            'data' => [
                'list' => $list
            ]
        ]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = json_decode($params['data'], true);
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    $this->handleSkuPrice();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $nodeList = \app\admin\model\UserRule::getTreeList();
        $this->assignconfig("nodeList", $nodeList);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->goods = $this->getGoods($row);
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = json_decode($params['data'], true);

                $result = false;
                Db::startTrans();
                try {
                    $row->allowField(true)->save($params);
                    $result = true;
                    $this->handleSkuPrice();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $rules    = explode(',', $row['rules']);
        $nodeList = \app\admin\model\UserRule::getTreeList($rules);
        $this->assignconfig("nodeList", $nodeList);
        $this->assignconfig('row', $row);
        return $this->view->fetch();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk       = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            $this->handleSkuPrice();
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 更新sku价格
     * @return bool
     * @throws PDOException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function handleSkuPrice()
    {
        // 获取有vip价格的skuPrice
        $skuPriceList = Db::name('shopro_goods_sku_price')
            ->where('vip <> "[]"')
            ->field(['id', 'vip'])
            ->select();

        if (empty($skuPriceList)) {
            return false;
        }

        $groupList = Db::name('user_group')
            ->where(['is_vip' => 1])
            ->field(['id', 'name'])
            ->select();
        // 清空所有会员价格
        if (empty($groupList)) {
            foreach ($skuPriceList as $val) {
                Db::name('user_group')->update([
                    'id'  => $val['id'],
                    'vip' => json_encode([], JSON_UNESCAPED_UNICODE)
                ]);
            }

            return true;
        }

        // 商城价格sku价格列表
        foreach ($skuPriceList as $key => &$val) {
            $vipList = [];
            foreach ($groupList as $v) {
                $vipList[] = $this->getSkuPriceItem($v, json_decode($val['vip'], true));
            }

            $val['vip'] = json_encode($vipList, JSON_UNESCAPED_UNICODE);

            // 更新vip价格
            Db::name('shopro_goods_sku_price')->update(([
                'id'  => $val['id'],
                'vip' => $val['vip']
            ]));
        }

        return true;
    }

    /**
     * 获取vip价格某一项
     * @param $group
     * @param $arr
     * @return array
     */
    private function getSkuPriceItem($group, $arr)
    {
        $item = [];
        foreach ($arr as $v) {
            if ($group['id'] == $v['id']) {
                $item = [
                    'id'    => $group['id'],
                    'name'  => $group['name'],
                    'price' => $v['price']
                ];
            }
        }

        if (empty($item)) {
            $item = [
                'id'    => $group['id'],
                'name'  => $group['name'],
                'price' => 0
            ];
        }

        return $item;
    }


    private function getGoods($data)
    {
        if ($data['goods_ids'] != 0) {
            return \app\admin\model\shopro\goods\Goods::where('id', 'in', $data['goods_ids'])->field('id, title, image')->select();
        }
        return null;
    }

}
